package core

import (
	"go.uber.org/zap"
	"live-core/logging"
	"time"

	"github.com/geekerstar/libv/format/rtspv2"
)

func streamServerRunStreamDo(streamID string, channelID string) {
	var status int
	defer func() {
		if status != 2 {
			StreamManager.ChannelUnlock(streamID, channelID)
		}
	}()
	for {
		logging.ZapLog.Info("播放视频流")
		opt, err := StreamManager.ChannelControl(streamID, channelID)
		if err != nil {
			logging.ZapLog.Info("退出", zap.String("stream", streamID), zap.String("channel", channelID), zap.Error(err))
			return
		}
		if opt.OnDemand && !StreamManager.ClientHas(streamID, channelID) {
			logging.ZapLog.Info("无人观看停止拉取视频流", zap.String("stream", streamID), zap.String("channel", channelID))
			return
		}
		status, err = runStream(streamID, channelID, opt)
		if status > 0 {
			logging.ZapLog.Info("关闭视频流", zap.String("stream", streamID), zap.String("channel", channelID))
			return
		}
		if err != nil {
			logging.ZapLog.Error("视频流拉取失败，重试", zap.String("stream", streamID), zap.String("channel", channelID), zap.Error(err))
		}
		time.Sleep(2 * time.Second)

	}
}

func runStream(streamID string, channelID string, opt *ChannelST) (int, error) {
	keyTest := time.NewTimer(20 * time.Second)
	checkClients := time.NewTimer(20 * time.Second)
	//var preKeyTS = time.Duration(0)
	//var Seq []*av.Packet
	RTSPClient, err := rtspv2.Dial(rtspv2.RTSPClientOptions{URL: opt.URL, DisableAudio: true, DialTimeout: 3 * time.Second, ReadWriteTimeout: 5 * time.Second, Debug: opt.Debug, OutgoingProxy: true})
	if err != nil {
		return 0, err
	}
	StreamManager.ChannelStatus(streamID, channelID, ONLINE)
	defer func() {
		RTSPClient.Close()
		StreamManager.ChannelStatus(streamID, channelID, OFFLINE)
		StreamManager.StreamHLSFlush(streamID, channelID)
	}()
	if len(RTSPClient.CodecData) > 0 {
		StreamManager.ChannelCodecsUpdate(streamID, channelID, RTSPClient.CodecData, RTSPClient.SDPRaw)
	}
	logging.ZapLog.Info("连接RTSP成功", zap.String("stream", streamID), zap.String("channel", channelID))
	for {
		select {
		case <-checkClients.C:
			if opt.OnDemand && !StreamManager.ClientHas(streamID, channelID) {
				return 1, ErrorStreamNoClients
			}
			checkClients.Reset(20 * time.Second)
		case <-keyTest.C:
			return 0, ErrorStreamNoVideo
		case signals := <-opt.signals:
			switch signals {
			case SignalStreamStop:
				return 2, ErrorStreamStopCoreSignal
			case SignalStreamRestart:
				return 0, ErrorStreamRestart
			case SignalStreamClient:
				return 1, ErrorStreamNoClients
			}
		case signals := <-RTSPClient.Signals:
			switch signals {
			case rtspv2.SignalCodecUpdate:
				StreamManager.ChannelCodecsUpdate(streamID, channelID, RTSPClient.CodecData, RTSPClient.SDPRaw)
			case rtspv2.SignalStreamRTPStop:
				return 0, ErrorStreamStopRTSPSignal
			}
		case packetRTP := <-RTSPClient.OutgoingProxyQueue:
			keyTest.Reset(20 * time.Second)
			StreamManager.ChannelCastProxy(streamID, channelID, packetRTP)
		case packetAV := <-RTSPClient.OutgoingPacketQueue:
			if packetAV.IsKeyFrame {
				keyTest.Reset(20 * time.Second)
				//if preKeyTS > 0 {
				//	StreamManager.StreamHLSAdd(streamID, channelID, Seq, packetAV.Time-preKeyTS)
				//	Seq = []*av.Packet{}
				//}
				//preKeyTS = packetAV.Time
			}
			//Seq = append(Seq, packetAV)
			StreamManager.ChannelCast(streamID, channelID, packetAV)
		}
	}
}
